<template>
  <div id="app">
    <van-config-provider
      :theme-vars="{
        // 主题色
        buttonPrimaryBackground: '#1f60fb',
        buttonPrimaryBorderColor: '#1f60fb',

        // 标题栏
        navBarHeight: '50px',
        navBarBackground: '#1a1d29',
        navBarTitleTextColor: 'white',

        // 通知栏
        noticeBarBackground: '#1a1d29',
        noticeBarTextColor: 'white',
      }"
    >
      <router-view v-slot="{ Component }" v-if="isInit">
        <keep-alive :include="['cache']">
          <component :is="Component"></component>
        </keep-alive>
      </router-view>
    </van-config-provider>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useStore } from '@/store/index'
import { showToast, showError } from 'js/utils'
import ContractContext from 'js/ContractContext'
import Web3 from 'web3'
// import VConsole from 'vconsole'
// new VConsole()

const router = useRouter()
const route = useRoute()
const store = useStore()

const isInit = ref(false) // 是否已初始化

// 初始化钱包
async function initWallet() {
  const BINANCE_CHAIN_OBJECT = window.BinanceChain || window.ethereum

  if (typeof BINANCE_CHAIN_OBJECT === 'undefined') {
    isInit.value = false
    return showToast('请先安装Binance Wallet')
  }

  // 打开钱包
  BINANCE_CHAIN_OBJECT.enable()
  BINANCE_CHAIN_OBJECT.on('accountsChanged', onAccountChange)
  BINANCE_CHAIN_OBJECT.on('disconnect', onDisconnect)

  // 获取Web3实例
  window.web3 = new Web3(BINANCE_CHAIN_OBJECT)

  // 获取Usdt合约实例
  window.usdtContract = new ContractContext('usdt')

  // 获取User合约实例
  window.userContract = new ContractContext('user')

  // 获取Order合约实例
  window.orderContract = new ContractContext('order')

  // 获取Pandax合约实例
  window.pandaxContract = new ContractContext('pandax')

  // 获取用户钱包地址
  window.fromAddress = await getFromAddress()

  // 获取用户隐藏钱包地址
  window.fromAddressHide = fromAddress.replace(
    fromAddress.substring(10, 32),
    '*******'
  )

  // 获取用户上级地址
  const parentAddress = await getParentAddress()

  if (route.path.includes('miner')) {
    // 矿机页面（单独做管理）
    renderView()
  } else {
    // 其他正常页面

    // 判断用户是否已注册
    if (parentAddress === '0x0000000000000000000000000000000000000000') {
      // 未注册
      router.replace(`/register?inviteId=${route.query.inviteId || ''}`)
      renderView()
    } else {
      // 已注册
      if (store.userInfo?.token) {
        // 已登录
        router.replace('/')
        renderView()
      } else {
        // 未登录
        router.replace('/login')
        renderView()
      }
    }
  }
}

// 获取用户钱包地址
function getFromAddress(accounts) {
  return new Promise(async (resolve, reject) => {
    try {
      console.log('获取用户钱包地址')

      const [fromAddress] = accounts ? accounts : await web3.eth.getAccounts()

      if (typeof fromAddress === 'undefined') {
        isInit.value = false
        showToast('请先解锁Binance Wallet')
        reject()
      }

      const fromAddressLowwerCase = fromAddress.toLowerCase()
      console.log(`获取用户钱包地址成功：${fromAddressLowwerCase}`)
      resolve(fromAddressLowwerCase)
    } catch (err) {
      showError('获取用户钱包失败')
      console.error('获取用户钱包失败')
      console.error(err)
      reject(err)
    }
  })
}

// 获取用户上级地址
function getParentAddress() {
  return new Promise(async (resolve, reject) => {
    try {
      console.log('获取用户上级地址')
      const parentAddress = await userContract.context.methods
        .getParent(fromAddress)
        .call()
      console.log(`获取用户上级地址成功：${parentAddress}`)
      resolve(parentAddress)
    } catch (err) {
      showError('获取用户上级地址失败')
      console.error('获取用户上级地址失败')
      console.error(err)
      reject(err)
    }
  })
}

// 账户变化
function onAccountChange(accounts) {
  isInit.value = false
  store.setUserInfo({})
  showToast('账户发生变化，请刷新页面')
  getFromAddress(accounts)
}

// 断开连接
function onDisconnect() {
  isInit.value = false
  return showToast('已断开链接')
}

// 渲染View层
function renderView() {
  isInit.value = false
  setTimeout(() => {
    isInit.value = true
  }, 500)
}

initWallet()
</script>

<style lang="scss">
@import 'style/index.scss';

#app {
  max-width: 400px;
  margin: 0 auto;
}
</style>
